package network_programming.np1_socket_and_serversocket;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class TCPClientDemo {
    private String ip;      // 服务器ip地址或主机名
    private int port;       // 服务器端口号
    private Socket socket;  // 客户端套接字，即两台机器之间通信的收发器
    TCPClientDemo(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }
    TCPClientDemo() {
        this("127.0.0.1", 9090);
    }
    public void start() {
        InetSocketAddress isa = new InetSocketAddress(ip, port);    //根据ip地址（主机名）和端口号创建套接字地址
        try {
            socket = new Socket(isa.getAddress(), port);    // 创建流套接字并将其连接到指定IP地址的指定端口号
//            socket = new Socket(ip, port);                  // 根据ip地址或主机名创建socket对象
            OutputStream os = socket.getOutputStream();     // 获取套接字输出流
            os.write("客户端a请求资源".getBytes());            // 发送数据
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket != null) {
                try {
                    socket.close();     // 释放资源
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        TCPClientDemo tcd = new TCPClientDemo();
        tcd.start();
    }
}
